<?php
/**
 * 商户店铺订单控制器
 * @author ezhu <ezhu@jipukeji.com>
 */

namespace Shop\Controller;

class OrderController extends CommonController{

  private $payment_type;
  private $o_status_text;
  private $is_packed_text = array(
    0 => '<span class="text-warning">未打包</span>',
    1 => '<span class="text-success">已打包</span>',
  );

  protected function _initialize(){
    parent::_initialize();
    //支付方式
    $this->payment_type = get_payment_type_text();
    $this->o_status_text = get_o_status_text();
    $this->assign('sign','order');
  }

  /**
   * 订单列表
   * @author ezhu <ezhu@jipukeji.com>
   */
  public function index(){
    // 记录当前列表页的Cookie
    Cookie('__forward__', $_SERVER['REQUEST_URI']);
    //商户订单列表
    $t_list = A('Order', 'Event')->getStorePageList();
    $map = array(
      'payment_type' => $this->payment_type,
      'o_status' => $this->o_status_text,
      'is_packed' => $this->is_packed_text,
    );
    int_to_string($t_list, $map);
    $list = A('Order', 'Event')->orderFormat($t_list);
    $this->list = $list;
    $this->meta_title = '订单列表';
    $this->display();
  }

  /**
   * 编辑订单
   * @author ezhu <ezhu@jipukeji.com>
   */
  public function edit($id = 0){
    if(IS_POST){
      $Order = D('Order');
      $data = $Order->create();
      if($data){
        if($Order->save() !== false){
          //记录行为
          //action_log('update_order', '$Order', $data['id'], UID);
          $this->success('更新成功', Cookie('__forward__'));
        }else{
          $this->error('更新失败');
        }
      }else{
        $this->error($Order->getError());
      }
    }else{
      $info = array();
      // 获取数据
      $info = M('Order')->field(true)->find($id);
      // 检测订单是否已取消
      if(!(is_array($info) || -1 == $info['status'])){
        $this->error = '订单已取消，不能编辑！';
        return false;
      }

      if(false === $info){
        $this->error('获取订单信息错误');
      }
      $this->assign('info', $info);
      $this->meta_title = '编辑订单信息';
      $this->display();
    }
  }

  /**
   * 更新部分字段前置方法：如果更改打包状态，验证订单状态
   * @author justin <justin@jipu.com>
   * @version 2015071010
   */
  function _before_updateField(){
    //判断输入的必须是数字
    $num = I('get.total_amount');
    if( ($num != null) && (!is_numeric($num) || $num < 0 ) )$this->error('请输入大于0的数字！');
    $order = M('StoreOrder')->where(array('id'=>I('get.id')))->find();
    if($order['is_packed'] == 1)$this->error('此订单已修改过支付价格！');
    $is_packed = I('get.is_packed', null);
    if(isset($is_packed)){   
      !in_array($order['o_status'] ,array(200 ,405) )  && $this->error('当前订单状态不允许更新打包状态！');
      $order['is_packed'] == 1 && $this->error('商品已打包！');
    }
  }

  /**
   * 更新部分数据
   * @author ezhu <ezhu@jipukeji.com>
   */
  public function updateField(){
    $res = D('Order')->updateField();
    if(!$res){
      $this->error(D('Order')->getError());
    }else{
      S('weixin_prepay_id_item_order_'.I('id'), null);    
      //商户表更新状态
      $data['is_packed'] = 1;
      M('StoreOrder')->where(array('id'=>I('id')))->save($data);
      $count = A('Home/Order','Event')->checkOrderCount(I('id'));
      $order_sn = M('StoreOrder')->where(array('id'=>I('id')))->getField('order_sn');
      $store_count = A('Home/Order','Event')->checkOrderStatusCount($data,$order_sn);
      //if($count == 1) M('Order')->where('order_sn='.$order_sn)->setField('total_amount',I('total_amount'));
      //平台状态更新
      if ($count == 1 || ($count == $store_count)) {
        M('Order')->where('order_sn='.$order_sn)->save($data);
        //记录行为
        action_log('update_order', 'order', I('id'), UID);
      }
      $this->success('修改成功', Cookie('__forward__'));
    }
  }

  /**
   * 查看订单
   * @author ezhu <ezhu@jipukeji.com>
   */
  public function view($id = 0,$order_sn = ''){

    if (!empty($order_sn)) {
      $store_id = $this->store_id;
      $id = M('StoreOrder')->where(array('store_ids'=>$store_id,'order_sn'=>$order_sn))->getField('id');
    }
    //获取订单信息
    $info = M('StoreOrder')->find($id);
    if(false === $info){
      $this->error('获取订单信息错误');
    }

    $order_id = M('Order')->where(array('order_sn'=>$info['order_sn']))->getField('id');

    // 获取支付方式
    $payment_type = M('Payment')->getFieldById(M('Order')->getFieldById($order_id, 'payment_id'), 'payment_type');
    if ($payment_type == null) {
      $info['payment_type_text'] = '余额支付';
    }else{
      $info['payment_type_text'] = get_payment_type_text($payment_type);
    }
    //订单商品信息
    $info['itemList'] = get_order_item($order_id);
    $item_ids = explode(',',$info['item_ids']);
    foreach ($info['itemList'] as $key => $value) {
        if (!in_array($value['item_id'],$item_ids)) {
          unset($info['itemList'][$key]);
        }
    }
    //订单商品数量
    $info['itemCount']['total_quantity'] = $info['total_quantity'];

    //分销店铺信息
    $info['sdp_shop'] = $info['sdp_uid'] > 0 ? M('Shop')->getByUid($info['sdp_uid']) : '';
    
    //付款信息
    $info['payment'] = M('Payment')->getById($info['payment_id']);

    //收货人信息
    $info['ship'] = M('OrderShip')->getByPaymentId($info['payment_id']);

    //物流信息
    $info['delivery'] = M('Ship')->where('status = 1')->getByOrderId($info['id']);

    //物流模板信息
    ($info['delivery_id'] > 0) && $info['delivery_tpl'] = M('DeliveryTpl')->getFieldById($info['delivery_id'], 'company');

    $info = A('Admin/Order','Event')->storeOrderFormat($info);
    $this->menu = A('Menu','Event')->menuList('Order/Index');
    $this->assign('info', $info);
    $this->meta_title = '订单详情';
    $this->display();
  }

  /**
   * 保存收货信息
   * @author tian <991269526@qq.com>
   */
  public function save($id = 0){
      if(IS_POST){
          $id = I('post.ship_id');
          $ship_name = I('post.ship_uname');
          $ship_mobile = I('post.ship_umobile');
          $ship_zipcode = I('post.ship_zipcode');
          $data = array(
            'ship_uname'=>$ship_name,
            'ship_mobile'=>$ship_mobile,
            'ship_zipcode'=>$ship_zipcode,
          );
        $ShipModel = M('OrderShip');
        //收货地址是否更改
        $ship_info = $ShipModel->find($id);
        if ( ($ship_info['ship_province'] == I('post.province')) && ($ship_info['ship_district'] == I('post.district')) && ($ship_info['ship_city'] == I('post.city')) && ($ship_info['ship_address'] == I('post.ship_address'))) {
          
        }else{
          $province = $this->_getAreaName(I('post.province'));
          $district = $this->_getAreaName(I('post.district'));
          $city = $this->_getAreaName(I('post.city'));
          $data['ship_area'] = $province.' '.$district.' '.$city;
          $data['ship_province'] = I('post.province');
          $data['ship_district'] = I('post.district');
          $data['ship_city'] = I('post.city');
          $data['ship_address'] = I('post.ship_address');
        }
        //开启事务
        //$ShipModel->startTrans();
        $rs = $ShipModel->where(array('id'=>$id))->save($data);
        //发票信息是否更改
        //$post_invoice = I('post.invoice_type').'&nbsp'.I('post.invoice_title').'&nbsp'.I('post.invoice_content');
        //$invoice = M('Order')->getFieldByOrderSn(I('post.order_sn'),'invoice_title');
        

        if($rs){
            $this->success('修改信息成功',U('Order/index'));
        }else{
            $this->success('返回订单页面',U('Order/index'));
        }
      }
  }

  private function _getAreaName( $id ){
    return M('Area')->getFieldById($id,'title');
  }

  /**
   * 商品清单
   * @author tian <991269526@qq.com>
   */
  public function printItem($id = 0){
      //获取订单信息
      $info = M('StoreOrder')->find($id);
      
      if(false === $info){
        $this->error('获取订单信息错误');
      }

      // 计算优惠金额
      $info['discount_amount'] = sprintf("%.2f", ($info['total_price'] + $info['delivery_fee'] - $info['total_amount'] - $info['finance_amount']));
      
      $order_id = M('Order')->where(array('order_sn'=>$info['order_sn']))->getField('id');

      // 获取支付方式
      $info['payment_type_text'] = get_payment_type_text(M('Payment')->getFieldById(M('Order')->getFieldById($order_id, 'payment_id'), 'payment_type'));

      //订单商品信息
      $info['itemList'] = get_order_item($order_id);
      $item_ids = explode(',',$info['item_ids']);
      foreach ($info['itemList'] as $key => $value) {
          if (!in_array($value['item_id'],$item_ids)) {
            unset($info['itemList'][$key]);
          }
      }
      //订单商品数量
      $info['itemCount']['total_quantity'] = $info['total_quantity'];
      
      //物流信息
      $info['delivery'] = M('Ship')->where('status = 1')->getByOrderId($info['id']);
      
      //物流模板信息
      ($info['delivery_id'] > 0) && $info['delivery_tpl'] = M('DeliveryTpl')->getFieldById($info['delivery_id'], 'company');
      
      //分销店铺信息
      $info['sdp_shop'] = $info['sdp_uid'] > 0 ? M('Shop')->getByUid($info['sdp_uid']) : '';
      
      //付款信息
      $info['payment'] = M('Payment')->getById($info['payment_id']);
      
      //收货人信息
      $info['ship'] = M('OrderShip')->getByPaymentId($info['payment_id']);

      $this->menu = A('Menu','Event')->menuList('Order/Index');
      $this->assign('info', $info);
      $this->meta_title = '商品清单';
      $this->display();

  }


  /**
   * 修改订单信息
   * @author tian <991269526@qq.com>
   */
  public function update($id = 0,$store_sn = ''){
      if (!empty($store_sn)) {
        $info = M('StoreOrder')->where(array('store_sn'=>$store_sn))->find();
      }else{
        $info = M('StoreOrder')->find($id);
      }
      // 计算优惠金额
      $info['discount_amount'] = sprintf("%.2f", ($info['total_price'] + $info['delivery_fee'] - $info['total_amount'] - $info['finance_amount']));
      // 获取支付方式
      $info['payment_type_text'] = get_payment_type_text(M('Payment')->getFieldById(M('Order')->getFieldById($info['id'], 'payment_id'), 'payment_type'));
      //订单商品信息
      $info['itemList'] = get_order_item($id);
      $info['itemCount'] = count_order_item($id);
      //付款信息
      $info['payment'] = M('Payment')->getById($info['payment_id']);
      //收货人信息
      $info['ship'] = M('OrderShip')->getByPaymentId($info['payment_id']);
      //物流信息
      $info['delivery'] = M('Ship')->where('status = 1')->getByOrderId($info['id']);
      //物流模板信息
      ($info['delivery_id'] > 0) && $info['delivery_tpl'] = M('DeliveryTpl')->getFieldById($info['delivery_id'], 'company');
      //分销店铺信息
      $info['sdp_shop'] = $info['sdp_uid'] > 0 ? M('Shop')->getByUid($info['sdp_uid']) : '';
      $info = A('Admin/Order','Event')->storeOrderFormat($info);
      //发票信息处理
      $invoice = explode('&nbsp',$info['invoice_title']);
      $this->assign('invoice',$invoice);
      $this->assign('info', $info);
      $this->meta_title = '订单修改';
      $this->display();
  }

  /**
   * 处理退款
   * @author ezhu <ezhu@jipukeji.com>
   */
  public function refund(){
    $order_id = I('order_id');
    $order = M('StoreOrder')->find($order_id);
    $id = M('Order')->where(array('order_sn'=>$order['order_sn']))->getField('id');
    if(empty($order)){
      die('订单不存在');
    }

    $count = A('Home/Order','Event')->checkOrderCount($order_id);

    //申请退款，已退货
    if(in_array($order['o_status'], array(300, 301, 302))){
      if(IS_POST){
        $new_status = I('post.to_status');
        
        //判断多个订单时候状态
        $store_count = A('Home/Order','Event')->checkOrderStatusCount(array($new_status),$order['order_sn']);

        //待买家退货
        if($new_status == 301){
          
          //商户方
          M('StoreOrder')->save(array('id' => $order_id, 'o_status' => $new_status)); 

          //平台方
          if ($count == 1 || ( ($count - 1) == $store_count )) {
              M('Order')->where('order_sn='.$order['order_sn'])->save(array('o_status' => $new_status));
           } 

          $this->success('退款申请已审核');

        }elseif($new_status == 303){
          // 初始化退款事件
          if ($count == 1) {
            $refund_return = A('Refund', 'Event')->doit(array($order_id) , array($id) ,'refund');
          }else{
            $refund_return = A('Refund', 'Event')->doitNew(array($order_id), array($id) ,'refund');
          }
          
          if($refund_return['code'] == 200){
            $this->success($refund_return['info']);
          }else{
            $this->error($refund_return['info']);
          }
        }elseif($new_status == -1){
          $to_status = 0;
          //已支付
          $order['payment_time'] > 0 && $to_status = 200;
          //已发货
          $order['shipping_time'] > 0 && $to_status = 201;
          //已完成
          $order['complete_time'] > 0 && $to_status = 202;

          //商户方状态更改
          M('StoreOrder')->save(array('id'=>$order_id,'o_status' => $new_status));

          //平台方状态同步
          if ($count == 1 || ( ($count-1) == $store_count )) {
            M('Order')->where(array('order_sn'=>$order_sn))->save(array('o_status' => $new_status));
          }

          $this->success('已取消退款');

        //驳回处理
        }elseif($new_status == 405){
            $reason = I('post.reason');
            if(empty($reason)){
                $this->error('请输入驳回原因');
            }
            $order_sn = M('StoreOrder')->where(array('id'=>$order_id))->getField('order_sn');
            //商户端状态更改
            $rst = M('StoreOrder')->save(array('id' => $order_id, 'o_status' => $new_status));

            //平台方状态更改同步
            if ($count == 1 || ( ($count -1) == $store_count )) {
              M('Order')->where(array('order_sn'=>$order['order_sn']))->save(array('o_status' => $new_status));
            }

            if(!empty($reason) && $rst){
                $msgData['uid'] = UID;
                $msgData['to_uid'] = $order['uid'];
                $msgData['order_sn'] = $order_sn;
                $msgData['title'] = '退单驳回     订单号:'.$order_sn;
                $msgData['content'] = $reason;
                $msgData['status'] = 1;
                $msgData['create_time'] = NOW_TIME;

                $messagedata = array('refuse_message' => $reason);
                
                //商户端记录
                M('StoreOrder')->where('id='.$order_id)->setField($messagedata);

                //平台方状态更改同步
                if ($count == 1 || ( ($count-1) == $store_count )) {
                  M('Order')->where('id='.$id)->setField($messagedata);
                }

                M('Message')->add($msgData);
                
                action_log('update_'.CONTROLLER_NAME, CONTROLLER_NAME, $order_id, UID);
               // ($rst !== false) && $this->success('退款已驳回');;
            }
           ($rst !== false) && $this->success('退款已驳回');
        }else{
          $this->error('请选择操作');
        }
      }
      if($order['reship_info']){
        $order['reship_info_text'] = json_decode($order['reship_info'], true);
      }
      $this->order = $order;
      $this->display();
    }else{
      die('当前状态不允许操作');
    }
  }
  
  /**
   * 商户订单重组排序
   * @param  [type] $data [description]
   * @return [type]       [description]
   */
  private function _orderListSort( $data ){
    $sort = array(
        'direction' => 'SORT_DESC', //排序顺序标志 SORT_DESC 降序；SORT_ASC 升序
        'field'     => 'create_time',       //排序字段
      );
    $arrSort = array();
    foreach($data AS $uniqid => $row){
         foreach($row AS $key=>$value){
             $arrSort[$key][$uniqid] = $value;
         }
     }
     if($sort['direction']){
         array_multisort($arrSort[$sort['field']], constant($sort['direction']), $data);
     }
     return $data;
    }
  }
